//
//  AirportService.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/2.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import Foundation
import Alamofire
import RxSwift

class AirportService {
    static let shared: AirportService = AirportService()
    private let httpService: AirportHttpService = AirportHttpService()
}

extension AirportService: AirportApi {
    
    func fechAirports() -> Single<AirportResponse> {
        return Single.create { (single) -> Disposable in
            do {
                try AirportHttpRouter.getAirports
                    .request(usingService: self.httpService)
                    .responseJSON { (response) in
                    do {
                        let airports = try AirportService.parseAirports(response: response)
                        single(.success(airports))
                    } catch {
                        single(.error(error))
                    }
                }
            } catch {
                single(.error(CustomError.error(messae: "Airport fetch failed")))
            }
            return Disposables.create()
        }
    }
}

extension AirportService {
    static func parseAirports(response: AFDataResponse<Any>) throws -> AirportResponse {
        guard
            let data = response.data,
            let airportResponse = try? JSONDecoder().decode(AirportResponse.self, from: data) else {
                throw CustomError.error(messae: "Invalid Json")
        }
        return airportResponse
    }
}
